<!--  -->
<template>
  <div class="contentbox flex-col dictionary-box">
    <el-card class="dictionary-margin flex-col">
      <el-descriptions
        title="工序字典维护"
        size="medium"
        :column="1"
        :colon="false"
      >
        <el-descriptions-item>
          <div class="taskview-top">
            <span>工序名称：</span>
            <el-input v-model="name" placeholder="请输入检索"> </el-input>
            <el-button type="primary" @click="initTable">搜索</el-button>
            <el-button
              type="primary"
              @click="
                () => {
                  (form = {
                    id: 0,
                    no: 0,
                    code: '',
                    name: '',
                    createTime: '',
                    title: '添加工序',
                  }),
                    $nextTick(() => {
                      $refs.processform.clearValidate();
                    });
                  formVisable = true;
                }
              "
              >添加</el-button
            >
          </div>
        </el-descriptions-item>
      </el-descriptions>
      <div class="taskmain flex-col">
        <el-table
          ref="multipleTable"
          :data="tableData"
          tooltip-effect="dark"
          height="100%"
        >
          <el-table-column
            type="index"
            label="序号"
            :index="indexMethod"
            width="120"
          >
          </el-table-column>
          <el-table-column prop="name" label="工序名称"> </el-table-column>
          <el-table-column prop="code" label="工序代码"> </el-table-column>
          <el-table-column prop="createTime" label="创建时间"
            ><template slot-scope="scope"
              >{{ ISOtoLocal(tableData[scope.$index]) }}<span></span
            ></template>
          </el-table-column>
          <el-table-column prop="address" label="操作">
            <template slot-scope="scope">
              <el-button
                type="text"
                @click="changeTable(tableData[scope.$index])"
                >修改</el-button
              >
              <el-button
                type="text"
                @click="deleteTable(tableData[scope.$index])"
                >删除</el-button
              >
            </template>
          </el-table-column>
        </el-table>
        <el-pagination
          background
          layout="->,total,sizes,prev, pager, next,jumper"
          :total="total"
          :current-page.sync="pageNum"
          :page-sizes="[20, 40, 60, 100]"
          :page-size="pageSize"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        >
        </el-pagination>
      </div>
    </el-card>
    <el-dialog v-model="form" :visible.sync="formVisable" width="30%">
      <span slot="title" style="text-align: center"
        >{{ form.title }}
        <el-divider></el-divider>
      </span>
      <el-form
        label-width="200px"
        :model="form"
        :rules="rules"
        ref="processform"
      >
        <el-form-item prop="name" label="工序名称：">
          <el-input
            v-model="form.name"
            placeholder="例如:制绒"
            style="width: 10vw"
          ></el-input>
        </el-form-item>
        <el-form-item prop="code" label="工序代码：">
          <el-input
            v-model="form.code"
            placeholder="例如:A010"
            style="width: 10vw"
          ></el-input>
        </el-form-item>
      </el-form>

      <span slot="footer" class="dialog-footer" style="text-align: center">
        <el-divider></el-divider>
        <div>
          <el-button @click="formVisable = false">取 消</el-button>
          <el-button
            type="primary"
            @click="
              () => {
                if (form.id == 0) {
                  subform(form, '/EQDictionary/InsertProcessInfo');
                } else {
                  subform(form, '/EQDictionary/UpdateProcessInfo');
                }
              }
            "
            >确 定</el-button
          >
        </div>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import $http from "../../utils/apiHelper";
const checkData = (rule, value, callback) => {
  if (value) {
    if (/[\u4E00-\u9FA5]/g.test(value)) {
      callback(new Error("不能包含中文!"));
    } else {
      callback();
    }
  }
  callback();
};
export default {
  data() {
    return {
      name: "",
      total: 0,
      pageNum: 1,
      pageSize: 20,
      topageSizetal: 1,
      formVisable: false,
      form: { id: 0, no: 0, code: "", name: "", createTime: "" },
      tableData: [],
      rules: {
        name: [
          { required: true, message: "工序名称不可为空", trigger: "blur" },
        ],
        code: [
          { required: true, message: "工序代码不可为空", trigger: "blur" },
          { validator: checkData, trigger: ["blur", "change"] },
        ],
      },
      searchConditionLast: {
        name: "",
        pageSize: 0,
        currentPage: 0,
      },
    };
  },
  methods: {
    indexMethod(index) {
      return (this.pageNum - 1) * this.pageSize + index + 1;
    },
    ISOtoLocal(isotime) {
      return this.$moment(new Date(isotime.createTime))
        .utcOffset("+08:00")
        .format("YYYY-MM-DD HH:mm:ss");
    },

    subform(form, url) {
      if (!form.name || !form.code) {
        return this.$message.error("工序名或工序代码不可为空");
      }
      if (!form.createTime) {
        let time = new Date();
        form.createTime = time;
      }
      var reg = new RegExp("[\\u4E00-\\u9FFF]+", "g");
      if (reg.test(form.code)) {
        return this.$message.error("工序代码不可包含中文");
      }
      $http.post(url, form).then((res) => {
        if (res.Data) {
          if (form.id == 0) {
            this.name = '';
            // 跳转到最后一页
            this.total = this.total + 1
            const lastPage = Math.ceil(this.total / this.pageSize);
            this.selectform(this.name,lastPage,this.pageSize)
            this.pageNum = lastPage;
          } else {
            this.tableData.splice(
              this.tableData.findIndex((r) => r.id == form.id),
              1,
              form
            );
          }

          this.$message.success("工序字典变更成功");
          this.formVisable = false;
        } else {
          this.$message.error(`工序字典变更失败, ${res.Message}`);
        }
      });
    },
    selectform(name, pageNum, pageSize) {
      let param = {
        name: name,
        pageSize: pageSize,
        currentPage: pageNum,
      };

      let isDifferent = false;
      for (let key in param) {
        if (
          key !== "currentPage" &&
          JSON.stringify(param[key]) !==
            JSON.stringify(this.searchConditionLast[key])
        ) {
          isDifferent = true;
          break;
        }
      }

      if (isDifferent) {
        this.pageNum = 1;
        param.currentPage = 1;
      }

      this.searchConditionLast = param;

      $http.post(`/EQDictionary/GetProcessInfo`, param).then((res) => {
        if (res.Data) {
          this.total = res.Data.totalCount;
          this.tableData = res.Data.pageData;
        } else {
          this.$message.error(`查询工序字典失败,${res.Message}`);
        }
      });
    },
    handleSizeChange(val) {
      this.pageSize = val;
      this.selectform(this.name, this.pageNum, this.pageSize);
    },
    handleCurrentChange(val) {
      this.pageNum = val;
      this.selectform(this.name, this.pageNum, this.pageSize);
    },
    initTable() {
      this.selectform(this.name, this.pageNum, this.pageSize);
    },
    deleteTable(value) {
      this.$confirm(`确定删除该工序?`, "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          $http
            .get(`/EQDictionary/DeleteProcessInfo?id=${value.id}`)
            .then((res) => {
              if (res.Data) {
                this.tableData = this.tableData.filter(
                  (item) => item.id != value.id
                );
                
                this.name = '';
                this.pageNum = 1;
                this.total = this.total-1;
                this.selectform(this.name, this.pageNum, this.pageSize);
                this.$message.success("删除工序字典成功");
              } else {
                this.$message.error(`删除工序字典失败,${res.Message}`);
              }
            });

        })
        .catch(() => {
          this.$message({
            type: "info",
            message: `已取消操作`,
          });
        });
    },
    changeTable(value) {
      this.$nextTick(() => {
        this.$refs.processform.clearValidate();
      });
      let { id, no, name, code, createTime } = value;
      this.form = { id, no, name, code, createTime, title: "修改工序" };
      this.formVisable = true;
    },
  },
  mounted() {
    this.initTable();
  },
};
</script>
